use askama_axum::{IntoResponse, Template};
use axum::{extract::{Path, Query, State}, response::{Html, Redirect}, Form};
use tower_cookies::Cookies;
use tower_sessions::Session;
use crate::{core::xerror::{XErrors, GLOBALERROR}, services::backend::taxon_service::TaxonService, types::backend::product_type::ProductListReq};
use crate::core::AppState;
use crate::types::common::Breadcrumb;
use crate::services::backend::product_service::ProductService;
use crate::types::backend::product_type::{ProductForm, ProductRow};
use crate::types::common::OptionRow;
use super::{AdminSession, ErrorTemplate};

#[derive(Template)]
#[template(path = "backend/product/list.html")]
struct ProductListTemplate {
    auth: AdminSession,
    breadcrumb: Breadcrumb,
    paginate: String,
    list: Vec<ProductRow>,
    taxons: Vec<OptionRow>
}


#[derive(Template)]
#[template(path = "backend/product/form.html")]
struct ProductFormTemplate {
    auth: AdminSession,
    breadcrumb: Breadcrumb,
    data: ProductForm,
    url: String, // action url 
    taxons: Vec<OptionRow>
}


/// 获取产品分页
pub async fn products_handler(State(state): State<AppState>, session: Session, Query(args):Query<ProductListReq>) -> impl IntoResponse {
    let auth = AdminSession::init(session).await;
    // 获取所有分类
    let taxons_res = TaxonService::get_option_taxons(&state.db).await;
    let taxons = match taxons_res {
        Ok(data) => data,
        Err(e) => {
            let template = ErrorTemplate{
                msg: e.to_string()
            };
            return axum::response::Html(template.render().unwrap())
        }
    };

    let res = ProductService::get_product_page(&state.db, &args).await;
    let breadcrumb = Breadcrumb {
        title: "产品管理".to_string(),
        sub_title: "产品列表".to_string(),
    };
   
    match res {
        Ok(data) => {
            let template = ProductListTemplate {
                auth,
                breadcrumb,
                paginate: data.paginate, 
                list: data.list,
                taxons
            };
            Html(template.render().unwrap())
        },
        Err(e) => {
            let template = ErrorTemplate {
                msg: e.to_string()
            };
            Html(template.render().unwrap())
        }
    }
   
}

/// 添加产品表单
pub async fn add_product_handler(State(state): State<AppState>, session: Session) -> impl IntoResponse {
    let auth = AdminSession::init(session).await;
    let breadcrumb = Breadcrumb {
        title: "产品管理".to_string(),
        sub_title: "添加产品".to_string(),
    };
    // 获取所有分类
    let taxons_res = TaxonService::get_option_taxons(&state.db).await;
    let taxons = match taxons_res {
        Ok(data) => data,
        Err(e) => {
            let template = ErrorTemplate{
                msg: e.to_string()
            };
            return axum::response::Html(template.render().unwrap())
        }
    };
    
    let template = ProductFormTemplate {
        auth,
        breadcrumb,
        data: ProductForm{
            tid: 0,
            name: "".to_string(), 
            seo_title: "".to_string(), 
            seo_keywords: "".to_string(), 
            seo_description: "".to_string(), 
            image: "".to_string(),
            url: "".to_string(),
            is_sale: 0,
            price: 0.0,
            sales: 0,
            hits: 0,
            content: "".to_string(),
        },
        url: "/backend/product/create".to_string(),
        taxons
    };
    return Html(template.render().unwrap());
}


/// 添加产品操作
pub async fn create_product_handler(
    State(state): State<AppState>, 
    cookies: Cookies,
    Form(form): Form<ProductForm>) -> Redirect {
    let error = XErrors::new();
    if form.name.is_empty() || form.tid == 0 {
        error.set_cookie_error(cookies, GLOBALERROR::PARAMINVALIDFAILED, "".to_string());
        return Redirect::to("/backend/product/create");
    }
    let res = ProductService::insert_product(&state.db, &form).await;
    match res {
        Ok(_) => {
            error.set_cookie_error(cookies, GLOBALERROR::ADDSUCCESS, "".to_string());
            return Redirect::to("/backend/product/list");
        },
        Err(e) => {
            let db_error = e.to_string();
            error.set_cookie_error(cookies, GLOBALERROR::ADDSUCCESS, db_error);
            return Redirect::to("/backend/product/list");
        }
    }
}

/// 修改产品表单
pub async fn edit_product_handler(State(state): State<AppState>, session: Session, Path(id): Path<i64>) -> impl IntoResponse {
    let auth = AdminSession::init(session).await;
    // 获取所有分类
    let taxons_res = TaxonService::get_option_taxons(&state.db).await;
    let taxons = match taxons_res {
        Ok(data) => data,
        Err(e) => {
            let template = ErrorTemplate{
                msg: e.to_string()
            };
            return axum::response::Html(template.render().unwrap())
        }
    };

    let res = ProductService::get_product_by_id(&state.db, id).await;
    let breadcrumb = Breadcrumb {
        title: "产品管理".to_string(),
        sub_title: "修改产品".to_string(),
    };
    match res {
        Ok(data) => {
            let template = ProductFormTemplate {
                auth,
                breadcrumb,
                data,
                url: format!("/backend/product/edit/{}", id),  
                taxons 
            };
            return Html(template.render().unwrap());
        },
        Err(e) => {
            let template = ErrorTemplate{
                msg: e.to_string(),
            };
            return Html(template.render().unwrap());
        }
    }
}

/// 修改产品操作
pub async fn update_product_handler(
    State(state): State<AppState>, 
    cookies: Cookies, 
    Path(id): Path<i64>,
    Form(form): Form<ProductForm>) -> Redirect {
    let error = XErrors::new();
    // 名称不能为空
    if form.name.is_empty() || form.tid == 0 {
        error.set_cookie_error(cookies, GLOBALERROR::PARAMINVALIDFAILED, "".to_string());
        return Redirect::to(format!("/backend/product/edit/{}", id).as_str());
    }

    let res = ProductService::update_product(&state.db, id, &form).await;
    match res {
        Ok(_) => {
            error.set_cookie_error(cookies, GLOBALERROR::UPDATESUCCESS, "".to_string());
            return Redirect::to("/backend/product/list");
        },
        Err(e) => {
            let db_error = e.to_string();
            error.set_cookie_error(cookies, GLOBALERROR::UPDATEFAILED, db_error);
            return Redirect::to("/backend/product/list");
        }
    }
}

/// 删除产品操作
pub async fn delete_product_handler(
    State(state): State<AppState>, 
    cookies: Cookies,
    Path(id): Path<i64>) -> Redirect {
    let error = XErrors::new();
    // 是否存在
    let exist = ProductService::exist_product_by_id(&state.db, id).await;
    let total = match exist {
        Ok(total) => total,
        Err(_) => 0,
    };
    if total == 0 {
        error.set_cookie_error(cookies, GLOBALERROR::RECORDNOTFOUND, "".to_string());
        return Redirect::to("/backend/product/list");
    }
    let res = ProductService::delete_product(&state.db, id).await;
    match res {
        Ok(_) => {
            error.set_cookie_error(cookies, GLOBALERROR::DELETESUCCESS, "".to_string());
            return Redirect::to("/backend/product/list");
        },
        Err(e) => {
            let db_error = e.to_string();
            error.set_cookie_error(cookies, GLOBALERROR::DELETEFAILED, db_error);
            return Redirect::to("/backend/product/list");
        }
    }
}